<?php

include("pChart/pData.class");
include("pChart/pChart.class");
require_once("database.php");

// Days to display
$days = 10;
$today = time();

if($_GET and isset($_GET['id']) and is_numeric($_GET['id'])){
  // Get points from database
  $points = array();
  for($i = 0; $i < $days; $i++){
    // Get day boundaries
    $day_min = $today - (($days - $i + 1) * 60 * 60 * 24);
    $day_max = $today - (($days - $i) * 60 * 60 * 24);
    
    // SQL to get the average price for a given day
    $sql = "
      SELECT AVG(price) AS avg_price
      FROM apartment
      WHERE date >= " . $day_min . "
      AND date < " . $day_max . "
      AND city_id = " . sql_escape($_GET['id']);
    
    $prices = query_select($sql);
    $average_price = $prices[0]['avg_price'];
    
    $city = query_select("
      SELECT name
      FROM city
      WHERE id = " . sql_escape($_GET['id'])
    );
    if(count($city) > 0){
      $cityname = $city[0]['name'];
    }
    else {
      $cityname = "INVALID CITY!";
    }
    
    // If average price exists, set the respective point to that price
    if(isset($average_price)){
      $points[$i] = $average_price;
    }
    // If the average price is not set, but it's not the first point, set the
    // respective point to the same value as the previous point - 1 IN ORDER
    // TO ADDRESS ISSUES WITH PCHART!
    else if($i != 0){
      $points[$i] = $points[$i-1] - .01;
    }
    // Else if the first price is not set (base case), just set it to min value for now
    else {
      $points[$i] = .5;
    }
  }
  
  //print_r($points);
  //print_r($prices);
  
  // Data set definition
  $DataSet = new pData;  
  $DataSet->AddPoint($points);  
  $DataSet->AddSerie();  
  $DataSet->SetSerieName("Average Price","Serie1");  
    
    
  //print_r($DataSet->GetData());
  //exit;
  // Initialise the graph  
  $Test = new pChart(450,455);  
  $Test->setFontProperties("Fonts/tahoma.ttf",10);  
  $Test->setGraphArea(40,30,380,430);  
  $Test->drawGraphArea(252,252,252);  
  $Test->drawScale($DataSet->GetData(),$DataSet->GetDataDescription(),SCALE_NORMAL,150,150,150,TRUE,0,2);
  //exit;  
  $Test->drawGrid(4,TRUE,230,230,230,255);  
  
  // Draw the line graph  
  $Test->drawLineGraph($DataSet->GetData(),$DataSet->GetDataDescription());  
  $Test->drawPlotGraph($DataSet->GetData(),$DataSet->GetDataDescription(),3,2,255,255,255);  
    
  // Finish the graph  
  $Test->setFontProperties("Fonts/tahoma.ttf",8);  
  $Test->drawLegend(45,35,$DataSet->GetDataDescription(),255,255,255);  
  $Test->setFontProperties("Fonts/tahoma.ttf",10);  
  $Test->drawTitle(60,22,"Average apartment prices in " . ucwords($cityname),50,50,50,385);  
  $Test->Stroke();
  
}


?>  
  